<template>
  <div class="comment">
    <lazy-component>
    <div v-for="item in commentsLi" :key="item.id" v-lazy="item">
      <div class="headImg"><img :src="item.headimg" alt=""></div>
      <div class="user-like">
        <span class="user-name">{{item.u_name}}</span>
        <div>
          <van-icon name="good-job-o" @click="clickLike(item.id)" />
          <span class="like-count">{{item.likes}}</span>
        </div>
      </div>
      <p class="comment-con">{{item.title}}</p>
      <div class="time">{{getTime(item.time)}}</div>
    </div>
    </lazy-component>
  </div>
</template>
<script>
export default {
  data: () => ({
    commentsLi: [ ]
  }),
  props: { id: { type: String }, refreshcom: { type: Boolean } },
  created () {
    // 获取新闻id下的评论
    this.getComment(this.id)
  },
  methods: {
    async getComment (cid) {
      const { data: { status, data } } = await this.$http.get('/api/getcomment/' + cid)
      if (status !== 0) {
        return console.log('错误')
      }
      this.commentsLi = []
      data.forEach(item => {
        this.$set(item, 'iLike', false)
        // 放入新闻id对应的评论
        if (item.new_id === Number(cid)) {
          this.commentsLi.push(item)
        }
      })
    },
    getTime (time) {
      return this.getFormate(time)
    },
    clickLike (cid) {
      this.commentsLi.forEach(item => {
        if (item.id !== cid) {
          return
        }
        if (item.iLike) {
          item.likes--
          this.likeCount(cid, -1)
          event.target.classList.add('van-icon-good-job-o')
          event.target.classList.remove('van-icon-good-job')
          item.iLike = false
        } else {
          item.iLike = true
          item.likes++
          this.likeCount(cid, 1)
          event.target.classList.add('van-icon-good-job')
          event.target.classList.remove('van-icon-good-job-o')
        }
      })
    },
    async likeCount (cid, num) {
      const { data: { status } } = await this.$http.get(`/api/addlike/${cid}/${num}`)
      if (status !== 0) {
        return console.log('错误')
      }
    },
    reComment (refresh) {
      if (!refresh) {
        return
      }
      this.getComment(this.id)
      this.$emit('refreshCom', false)
    }
  }
}
</script>
<style lang="less" scoped>
.comment{
  margin-top: 10px;
  padding: 10px;
  border-top: 8px solid #eee;
  .headImg{
    float: left;
    margin-right: 5px;
    overflow: hidden;
    height: 40px;
    width: 40px;
    border-radius: 50%;
    background: #bbb;
    img{
      width: 100%;
      height: 100%;
    }
  }
  .user-name{
    color: blue;
  }
  .user-like{
    display: flex;
    justify-content: space-between;
  }
  .comment-con{
    margin: 10px 45px;
    width: 75%;
  }
  .time{
    margin-left: 45px;
    font-size: 14px;
  }
}
</style>
